package com.jy.phonemng.biz.minaserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.jy.phonemng.biz.minacodec.ImageCodecFactory;
import com.jy.phonemng.biz.minacodec.ImageRequestDecoder;
import com.jy.phonemng.biz.minacodec.ImageRequestEncoder;

public class ImageServer {
    public static final int  PORT        = 33789;
    private final static int maxNioCache = 50 * 1024 * 1024;

    public static void main(String[] args) throws IOException {

        ImageServerIoHandler handler = new ImageServerIoHandler();

        NioSocketAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getSessionConfig().setReadBufferSize(maxNioCache);
        acceptor.getSessionConfig().setReceiveBufferSize(maxNioCache);
        acceptor.getSessionConfig().setSendBufferSize(maxNioCache);

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        // add an IoFilter .  This class is responsible for converting the incoming and 
        // outgoing raw data to ImageRequest and ImageResponse objects
        ImageCodecFactory factory = new ImageCodecFactory(new ImageRequestDecoder(
            Charset.forName("utf-8")), new ImageRequestEncoder(Charset.forName("utf-8")));
        acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(factory));

        /*ObjectSerializationCodecFactory objSFactory = new ObjectSerializationCodecFactory();
        objSFactory.setDecoderMaxObjectSize(maxNioCache);
        objSFactory.setEncoderMaxObjectSize(maxNioCache);
        acceptor.getFilterChain().addLast("mychain", new ProtocolCodecFilter(objSFactory));*/

        DefaultIoFilterChainBuilder filterChainBuilder = acceptor.getFilterChain();
        filterChainBuilder.addLast("threadPool",
            new ExecutorFilter(Executors.newCachedThreadPool()));
        // set this NioSocketAcceptor's handler to the ImageServerHandler
        acceptor.setHandler(handler);

        // Bind to the specified address.  This kicks off the listening for 
        // incoming connections
        acceptor.bind(new InetSocketAddress(PORT));

        System.out.println("Step 1 server is listenig at port " + PORT);
    }
}
